package com.offcn.controller;

import com.github.pagehelper.PageInfo;
import com.offcn.bean.User;
import com.offcn.service.UserService;
import com.offcn.utils.ReturnResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("user")
@ResponseBody
public class UserController {
    @Autowired
    private UserService userService;

    //登录
    @RequestMapping("login")
    public ReturnResult login(String uname, String password, HttpSession session){
        User user = userService.getUserByUnamePwd(uname, password);
        if(user!=null){
            if(user.getStatus()==2){
                //未被冻结
                if(user.getUtype() == 1){
                    //是管理员可以登陆
                    //信息正确，可以登陆
                    session.setAttribute("userSession",user);
                    return new ReturnResult("【"+user.getUname()+"】登陆成功，即将跳转到主页!",1,null);
                }else{
                    //不是管理员
                    return new ReturnResult("当前页面只能管理员登录!",-1,null);
                }
            }else{
                //被冻结
                return new ReturnResult("您的账号被冻结，请联系管理员!",-1,null);
            }
        }else{
            //信息错误
            return new ReturnResult("用户名或密码错误!",-1,uname);
        }

    }

    //退出
    @RequestMapping("logout")
    public ReturnResult logout(HttpSession session){
        try {
            session.invalidate();
            return new ReturnResult("退出成功,即将返回登录页面!",1,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //已进入某些页面，立即判断是否登陆
    @RequestMapping("getUserSession")
    public int getUserSession(HttpSession session){
        User userSession = (User) session.getAttribute("userSession");
        if(userSession!=null){
            return 1;
        }else{
            return -1;
        }
    }

    //获取用户列表的方法
    @RequestMapping("getUserList")
    public PageInfo<User> getUserList(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(value = "uname", defaultValue = "") String uname) {
        PageInfo<User> userPageInfo = userService.userPageInfo(pageNo, uname);
        return userPageInfo;
    }

    //改变用户状态的方法(解冻和冻结)
    @RequestMapping("modefyStatus")
    public ReturnResult modefyStatus(Integer status,Integer uid){
        return userService.modefyStatus(status,uid);
    }

    //查看用户详情的方法
    @RequestMapping("queryDetails")
    public User queryDetails(Integer uid){
        return userService.queryDetails(uid);
    }
}
